﻿//自定义的ajax，默认async:true,cache:false,dataType:json,event:success,beforeSend,complete
//TODO:error event
//$.myAjax = function (url, data, type, successfn, beforefn, completefn) {
//
//	data = (data == null || data == "" || typeof (data) == "undefined") ? { "date": new Date().getTime() } : data;
//
//    $.ajax({
//        url: url,
//        data: data,
//        type: type,
//        cache: false,
//        async: true,
//        dataType: 'json',
//        success: function (d) {
//
//            successfn(d);
//
//        },
//        //error: function (e) {
//        //    errorfn(e);
//        //},
//        beforeSend: function (s) {
//
//            beforefn(s);
//        },
//        complete: function (c) {
//
//            completefn(c);
//
//        }
//
//    })
//
//};


$.myAjax = function (url, data, type, successfn, beforefn, completefn,errorfn) {

	data = (data == null || data == "" || typeof (data) == "undefined") ? { "date": new Date().getTime() } : data;

    $.ajax({
        url: url,
        data: data,
        type: type,
        cache: false,
        async: true,
        dataType: 'json',
        success: function (d) {

            successfn(d);

        },
        error: function (e) {
            errorfn(e);
        },
        beforeSend: function (s) {

            beforefn(s);
        },
        complete: function (c) {

            completefn(c);

        }

    })

};




function myNoty(msg, status) {

    //var options;
	

	
	if(status==10001)
	{
		var type="success";
		
		var closewith="hover";
	}
    if(status!=10001)
    {
        var type="warning";

        var closewith="hover";
    }
	
    //options = { "text": msg, "layout": "center", "type": type, "animateOpen": { "opacity": "show", "speed": 100 }, "timeout": timeout, "animateClose": { "opacity": "hide", "speed": 100 } };
    var options = {
        text: msg,
        timeout: false,
        type: type,
        theme: 'relax',
        layout: 'topRight',
        closeWith: [closewith],
        timeout: 2000,
        maxVisible: 10,
        animation: {
            open: { height: 'toggle' }, // jQuery animate function property object
            close: { height: 'toggle' }, // jQuery animate function property object
            //open: 'animated bounceInDown', // Animate.css class names
            //close: 'animated bounceOutRight', // Animate.css class names
            easing: 'swing', // unavailable - no need
            speed: 500 // unavailable - no need
        }
    };
    noty(options);
    //noty(options);


}

function getParameterByName(name) {

    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
};

//检测null
function myNotyNull(msg,value)
{
    if (value == null || value == "") {
        myNoty(msg, 'failed');

        return false;
    }
    else {

        return true;
    }
}

	

function reload() {
    window.location.reload();
}


function showLoadingImg() {

    var html = '<div id="loadingAjaxImg" style="position:absolute;top:50%;left:50%;"><img src="../images/loading.gif" /></div>';
    $(document.body).prepend(html);
    document.body.style.cursor = "wait";

}

//加载到''内容之后
function showAppendLoadingImg(appendId) {

    var html = '<span id="loadingAjaxImg" style=""><img src="../images/loading.gif" /></span>';
    $('#' + appendId).append(html);
    document.body.style.cursor = "wait";

}
//加载至""外部之后
function showAfterLoadingImg(appendId) {

    var html = '<span id="loadingAjaxImg" style=""><img src="../images/loading.gif" /></span>';
    $('#' + appendId).after(html);
    document.body.style.cursor = "wait";

}

function hideLoadingImg() {

    $('#loadingAjaxImg').remove();

    document.body.style.cursor = "default";
}

function showLoading(obj)
{
	
	document.body.style.cursor = "wait";
	$('#'+obj).show();
	
}
function hideLoading(obj)
{
	
	document.body.style.cursor = "default";
	$('#'+obj).hide();
	
}


//显示mask，以免用户误操作。
function showMaskLayer(msg) {

    var html1 = '<div id="popWindow" class="popWindow"></div> ';

    var html2 = '<div id="maskLayer" class="maskLayer">' + msg + '</div>';

    $(document.body).prepend(html1);

    $(document.body).prepend(html2);
}

function hideMaskLayer() {

    $('#popWindow').remove();

    $('#maskLayer').remove();

}



function sleep(n) { //n表示的毫秒数
    var start = new Date().getTime();
    while (true) if (new Date().getTime() - start > n) break;
}
//延时执行
var delayDo = (function () {
    var timer = 0;
    return function (callback, time) {
        clearTimeout(timer);
        timer = setTimeout(callback, time);
    };
})();


// shop edit,company edit
function reloadLogo(path) {


    $('#img-container').find('a').prop('href', MONGO_IMG_URL + path);

    $('#img-container').find('img').prop('src', MONGO_IMG_URL + path);


}

function removeFilesFromMongoDB(fileNames)
{
    $.myAjax('/Util/removeFilesFromMongo', { fileNames: fileNames }, 'post',
        
        
        
        function (data) {
            myNoty(data.msg,data.success);

        },
        function () {

        },
        function () {

        }
        
        
        
        
        
        
        
        )
}

function refreshTreeActivateNode(treeId,nodeId)
{
    var tree=$("#"+treeId);

    var node = tree.jstree("get_node", nodeId);

    for (var i = 0; i < node.parents.length; i++) {
        var pp = tree.jstree("get_node", node.parents[i]);

        if (pp.id == "#") {
            tree.jstree('refresh');

            return;
        }


        if (pp.original.attr.Activate == true) {

            tree.jstree("refresh_node", pp.id);


            return;
        }
    }
}


function getFullNodeName(treeId, nodeId)
{
    var tree = $("#" + treeId);

    var node = tree.jstree("get_node", nodeId);

    var fullName = node.text;

    for (var i = 0; i < node.parents.length; i++) {
        var pp = tree.jstree("get_node", node.parents[i]);

        if (pp.id != "#") {
            
            fullName = pp.text + '>' + fullName;

            
        }
        
    }

    return fullName;
}

function refreshTreeNode(treeId, nodeId)
{
    var tree = $("#" + treeId);

    var p=tree.jstree("get_node", nodeId).parent;

    if(p=="#")
    {
       tree.jstree('refresh');
    }
    else
    {
        tree.jstree("refresh_node", p);
    }
}

function refreshTreeCreateNode(treeId, nodeId)
{
    var tree = $("#" + treeId);

    if (nodeId == null) {
        tree.jstree("refresh");
    }
    else {

        tree.jstree("refresh_node", nodeId);

        //tree.jstree("select_node", nodeId, false, true);

        tree.jstree("open_node", nodeId, null, true);
    }
}


//删除重复
Array.prototype.delRepeat = function () {
    var newArray = [];
    var provisionalTable = {};
    for (var i = 0, item; (item = this[i]) != null; i++) {
        if (!provisionalTable[item] && item!="") {
            newArray.push(item);
            provisionalTable[item] = true;
        }
    }
    return newArray;
}

//删除其中一个
Array.prototype.delId = function (id) {
       

    for (var i = 0; i < this.length; i++) {
        if (this[i] == id) {
            this.splice(i, 1);
            break;
        }
    }

    return this;
}


function fileUploadFinal(btn,onSuccess, onStart,fileSize,uploader) {
    
    $('#'+btn).uploadify({

        'buttonText': '请选择上传文件',
        'swf': '../../Scripts/elink/js/uploadify/uploadify.swf',
        'uploader': uploader,
        'fileSizeLimit': fileSize,
        'fileTypeDesc': IMAGE_FILE_TYPE_DESC,
        'fileTypeExts': IMAGE_FILE_TYPE_EXTS,
        'onUploadSuccess': 
            function (file, data, response) {

                onSuccess(file, data, response);

            },
        'onUploadStart': function () {

            onStart();

            showAfterLoadingImg('file_upload');
        },
        'onUploadComplete': function () {

            hideLoadingImg();
        }
    });
}

function fileUpload(onSuccess,onStart){

    fileUploadFinal('file_upload', onSuccess, onStart, IMAGE_SIZE_LIMIT, '/Util/UploadFileToMongo');

}

function fileUpload(onSuccess, onStart,fileSize) {

    fileUploadFinal('file_upload', onSuccess, onStart, fileSize, '/Util/UploadFileToMongo');

}


function myHover(obj)
{
    //鼠标悬浮图片效果，模拟hover
    $(obj).on('mouseover mouseout', '.portfolio-item a', function (e) {


        if (event.type == "mouseover") {
            jQuery(this).find('.portfolio-item-hover').animate({
                "opacity": 0.8
            }, 100, 'easeInOutCubic');
        } else if (event.type == "mouseout") {
            jQuery(this).find('.portfolio-item-hover').animate({
                "opacity": 0
            }, 100, 'easeInOutCubic');
        }
    });

    $(obj).on('mouseover mouseout', '.portfolio-item a', function (e) {

        if (event.type == "mouseover") {
            jQuery(this).find(".fullscreen").stop().animate({ 'top': '60%', 'opacity': 1 }, 250, 'easeOutBack');
        } else if (event.type == "mouseout") {
            jQuery(this).find(".fullscreen").stop().animate({ 'top': '65%', 'opacity': 0 }, 150, 'easeOutBack');
        }
    });
}


function addValToInput(obj,val)
{
	var ids = [];

    if ($(obj).val() != '') {
        ids = $(obj).val().split(',');
    }

    ids.push(val);
    
    ids=ids.delRepeat();

    $(obj).val(ids.join(','));

}

function removeValFromInput(obj,val)
{
	
	var ids = [];

    if ($(obj).val() != '') {
     
    	ids = $(obj).val().split(',');
    
    	ids = ids.delId(val);

    	$(obj).val(ids.join(','));
    }
}

String.prototype.format = function() {
	  var str = this;
	  for (var i = 0; i < arguments.length; i++) {       
	    var reg = new RegExp("\\{" + i + "\\}", "gm");             
	    str = str.replace(reg, arguments[i]);
	  }
	  return str;
	}


$.myPost=function(url, data, successfn){
	
	
	data = (data == null || data == "" || typeof (data) == "undefined") ? { "date": new Date().getTime() } : data;

    $.ajax({
        url: url,
        data: data,
        type: 'post',
        cache: false,
        async: true,
        dataType: 'json',
        success: function (d) {

            successfn(d);

        },
        error: function (e) {
            myNoty('请求错误。',10002);
        },
        beforeSend: function (s) {
        	
        	$.noty.closeAll();
        	
        	addLoading();
        },
        complete: function (c) {

        	removeLoading();

        }

    })
	
	
	
}

function addLoading()
{
	var d='<div	style="position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 98999; background: rgba(0, 0, 0, 0.7);" id="loading">'
			+'<div class="spiner-example">'
				+'<div class="sk-spinner sk-spinner-three-bounce">'
				+	'<div class="sk-bounce1"></div>'
				+	'<div class="sk-bounce2"></div>'
				+	'<div class="sk-bounce3"></div>'
				+'</div>			</div>		</div>';
	
	$('body').append(d);
	
}

function removeLoading()
{
	$('#loading').remove();
}
